package com.yff.tuan.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yff.tuan.mapper.CarMapper;
import com.yff.tuan.mapper.CbrandMapper;
import com.yff.tuan.mapper.CmodelMapper;
import com.yff.tuan.model.Car;
import com.yff.tuan.model.CarExample;
import com.yff.tuan.model.CarExample.Criteria;
import com.yff.tuan.model.Cbrand;
import com.yff.tuan.model.CbrandExample;
import com.yff.tuan.model.Cmodel;
import com.yff.tuan.model.CmodelExample;
import com.yff.tuan.service.BrandService;
import com.yff.tuan.service.CarService;
import com.yff.tuan.service.ModelService;
import com.yff.tuan.util.Page;

@Component
public class BrandServiceImpl implements BrandService {
	@Autowired
	CbrandMapper cbrandMapper;
	@Autowired
	CmodelMapper cmodelMapper;
	

	@Override
	public List<Cbrand> query(CbrandExample example) {
		return cbrandMapper.selectByExample(example);
	}


	@Override
	public Cbrand find(Integer id) {
		Cbrand cbrand = cbrandMapper.selectByPrimaryKey(id);
		if(null != cbrand) {
			CmodelExample example = new CmodelExample();
			example.createCriteria().andBrandIdEqualTo(cbrand.getId());
			List<Cmodel> cmodels = cmodelMapper.selectByExample(example);
			cbrand.setCmodels(cmodels);
		}
		return cbrand;
	}


	@Override
	public List<Cmodel> queryCmodel(Integer brandId) {
		return null;
	}


	@Override
	public boolean add(Cbrand cbrand) {
		int id = cbrandMapper.insert(cbrand);
		List<Cmodel> cmodels = cbrand.getmAdd();
		if(null != cmodels && !cmodels.isEmpty()) {
			for(Cmodel cmodel:cmodels) {
				cmodel.setBrandId(cbrand.getId());
				cmodelMapper.insert(cmodel);
			}
		}
		return id>0?true:false;
	}


	@Override
	public boolean update(Cbrand cbrand) {
		int id = cbrandMapper.updateByPrimaryKey(cbrand);
		List<Cmodel> cmodelAdd = cbrand.getmAdd();
		List<Cmodel> cmodelUpdate = cbrand.getmUpdate();
		if(null != cmodelAdd && !cmodelAdd.isEmpty()) {
			for(Cmodel cmodel:cmodelAdd) {
				cmodel.setBrandId(cbrand.getId());
				cmodelMapper.insert(cmodel);
			}
		}
		if(null != cmodelUpdate && !cmodelUpdate.isEmpty()) {
			for(Cmodel cmodel:cmodelUpdate) {
				cmodelMapper.updateByPrimaryKey(cmodel);
			}
		}
		return id>0?true:false;
	}


}
